<?php


namespace App\Service\client;


use App\Common\RedisUtils;
use App\Common\Res;
use App\Common\SendMsgUtils;
use App\Common\StringUtils;
use App\Constants\ConstCode;
use App\Constants\ErrorCode;
use App\Model\form\WeworkAccountTrait;
use App\Model\form\WeworkOperationTrait;
use App\Model\TaskAccount;
use App\Model\WeworkSubject;
use App\Request\client\AccountRequest;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class accountService
{
    use  Res, RedisUtils, StringUtils, SendMsgUtils, WeworkAccountTrait, WeworkOperationTrait;

    /**
     *同步采集号信息
     * @param array $params
     * @return array
     */
    public function appUploadAccountInfo($fd, array $params): array
    {
        ApplicationContext::getContainer()->get(AccountRequest::class)->validated($params['data'], __FUNCTION__);
        $params_data = $params['data'];
        Db::beginTransaction();
        try {
            /*根据token查询redis是否存在数据*/
            $token = trim($params['token']);
            $deviceInfo = $this->hGet($this->hKey, $token);
            if (empty($deviceInfo)) {
                return $this->Error(ErrorCode::ERROR, '设备登录信息错误');
            }
            $deviceInfoArr = json_decode($deviceInfo, true);
            $account = $this->getWeworkAccountInfo(['marketUserId' => $deviceInfoArr['marketUserId']]);
            if (!empty($account) && $account->mobile != $params_data['phone']) {
                /*置空原账号，绑定新账号*/
                $account->marketUserId = '';
                $account->save();
            }
            /*如果主体不为空*/
            if (!empty($params['name'])) {
                $subject = WeworkSubject::where(['name' => trim($params['name'])])->first();
                if (empty($subject)) {
                    $subject_id = WeworkSubject::insertGetId([
                        'name' => trim($params['name']),
                        'created_at' => date("Y-m-d H:i:s", time())
                    ]);
                    $params_data['subject_id'] = $subject_id;
                } else {
                    $params_data['subject_id'] = $subject['id'];
                }
            }
            $params_data['mobile'] = $params_data['phone'];
            $params_data['marketUserId'] = $deviceInfoArr['marketUserId'];
            $this->upOrCreatWeworkAccount(['mobile' => $params_data['phone']], $params_data);

            $data['status'] = 1;
            $data['msg'] = '账号信息同步成功';
            $result = $this->sendAppUploadAccountInfo($fd, $data);
            Db::commit();
            return $this->Success('账号信息同步成功', $result);
        } catch (\Throwable $ex) {
            Db::rollBack();
            $data['status'] = 0;
            $data['msg'] = $ex->getMessage();
            $result = $this->sendAppUploadAccountInfo($fd, $data);
            return $this->Error(ErrorCode::ERROR, '账号信息同步失败' . $ex->getMessage());
        }
    }


    /**
     * 处理账号异常
     */
    public function appUploadAccountError($fd, array $params): array
    {
        ApplicationContext::getContainer()->get(AccountRequest::class)->validated($params['data'], __FUNCTION__);
        $params_data = $params['data'];
//        Db::beginTransaction();
//        try {
        /*根据token查询redis是否存在数据*/
        $token = trim($params['token']);
        $deviceInfo = $this->hGet($this->hKey, $token);
        if (empty($deviceInfo)) {
            return $this->Error(ErrorCode::ERROR, '设备登录信息错误');
        }
        $deviceInfoArr = json_decode($deviceInfo, true);
        $account = $this->getWeworkAccountInfo(['mobile' => $params_data['phone']]);
        $restrict_status = $this->getRestrictStatus(trim($params_data['restrict_time']));
        /*账号状态修改，任务账号状态修改*/
        $restrict_content = !empty($params_data['restrict_content']) ? $params_data['restrict_content'] : '账号异常';
        if (!empty($account)) {
            $account->restrict_status = $restrict_status;
            $account->restrict_content = $restrict_content;
            if ($restrict_status == ConstCode::ACCOUNT_RESTRICT_STATUS_TWO) {
                $restrict_time = $this->getRestrictTime($params_data['restrict_time']);
                $account->restrict_start_time = $restrict_time['start_time'];
                $account->restrict_end_time = $restrict_time['end_time'];
            }
            $res = $account->save();
            if ($res) {
                /*处理相关账号任务信息*/
                $task_account = TaskAccount::where(['account_id' => $account['id']])->first();
                if (!empty($task_account)) {
                    $task_account->restrict_status = $restrict_status;
                    $task_account->restrict_content = $restrict_content;
                    $task_account->status = ConstCode::NO_USE;
                    $task_account->save();
                }
                $messageList = $this->hGetAll('message');
                if (!empty($messageList)) {
                    foreach ($messageList as $key => $value) {
                        $message = json_decode($value, true);
                        if ($message['marketUserId'] == $account['marketUserId']) {
                            $this->zRem('messageKey', $key);
                            $this->hDel('message', $key);
                        }
                    }
                }
            }
        }
//            Db::commit();
        return $this->Success('账号异常信息处理成功');
//        } catch (\Throwable $ex) {
//            Db::rollBack();
//            return $this->Error(ErrorCode::ERROR, '账号异常信息处理失败' . $ex->getMessage());
//        }
    }


}